﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Website;
using System.Web;
using MvcEngine.Core.Helpers;

namespace MvcEngine.Core.Utils
{
    public static class InitUtils
    {
        public static void SetupSite() 
        {
            string sitedomain = HttpContext.Current.Request.Url.Host;
            Site site = null;

            if (sitedomain.Length > 0)
            {
                if (HttpRuntime.AppDomainAppVirtualPath != null && HttpRuntime.AppDomainAppVirtualPath.Length > 1)
                {
                    sitedomain = string.Concat(sitedomain, HttpRuntime.AppDomainAppVirtualPath);
                }
                site = SiteManager.Current.GetSiteByDomain(sitedomain);

                //If the domain cannot be matched with a website the default website is set as the current site.
                if (site == null)
                {
                    LogHelper.Current.WriteError(string.Format("Website for '{0}' domain was not found.", sitedomain));
                    HttpContext.Current.Response.Write("Requested site was not found.");
                    HttpContext.Current.Response.End();
                }
                else
                {
                    SiteContext.Current.Site = site;
                }
            }
            else 
            {
                LogHelper.Current.WriteError("Site domain is not present in the url.");
            }
        }
    }
}
